package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.aspectj.weaver.patterns.HasMemberTypePattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;

@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private  BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;
    @Override
    public TablePageInfo< CarPackageAudit > query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public void cancelApply(Long id) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //要先判断是撤销流程的状态是否是审核中的如果不是进行撤销就是非法操作
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            throw  new BusinessException("非法操作");
        }
        //如果不是这时修改审核流程为撤销状态
        carPackageAuditMapper.updateStatus(id,CarPackageAudit.STATUS_CANCEL);
        //将服务单项的审核状态修改为初始化
        serviceItemMapper.updateAuditStatus(carPackageAudit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        //删除流程实例,谁创建的流程实例就是用谁去删除 runtimeService
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"删除实例");
    }

    @Override
    public InputStream processImg(Long id) {
        //先根据id查询出来carPackageAudit 对象,判断获取
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        //BpmnInfo中存储由流程实例的id,激活高亮正需要流程实例的id

        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(carPackageAudit.getBpmnInfoId());
        if (bpmnInfo==null){
            throw new BusinessException("数据被丢到外太空了");
        }
        List< String > activeActivityIds= Collections.EMPTY_LIST;
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())){
            //使用的流程实例id
            activeActivityIds = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        }
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        //设置一个高亮点,和高亮线,以及
        InputStream inputStream = processDiagramGenerator.generateDiagram(
                bpmnModel,
                activeActivityIds,
                Collections.EMPTY_LIST,
                "宋体",
                "宋体",
                "宋体");
        return inputStream;
    }


    @Transactional
    @Override
    public void actionAudit(Long id, String info, Long auditStatus) {
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectByPrimaryKey(id);
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("非法操作" );
        }
        Map< String, Object > map = new HashMap<>();
        map.put("auditStatus",auditStatus);
        //获取当前任务
        Task currentTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
        String labels = carPackageAudit.getLabels();
        if (labels==null){
            labels= currentTask.getAssignee();
            carPackageAudit.setLabels(labels);
        }else {
            labels = labels+","+ currentTask.getAssignee();
            carPackageAudit.setLabels(labels);
        }
        //将获取到审批结果交给流程去判断,是否能够通,运行审批流程
        taskService.complete(currentTask.getId(),map);
        if (auditStatus==2L){
            //这里判断成功后又分为两种情况,有下一个节点和没有下一个节点
            Task nextTask = taskService.createTaskQuery().processInstanceId(carPackageAudit.getInstanceId()).singleResult();
            if (nextTask!=null){
                //需要获取next个任务的审核人然后设置到carPackageAudit audtorId 及 label的拼接
               // labels= labels+"," + nextTask.getAssignee();
                carPackageAudit.setLabels(labels);
                carPackageAudit.setAuditorId(Long.valueOf(nextTask.getAssignee()));
                carPackageAudit.setInfo(carPackageAudit.getInfo()+"<br>"+ ShiroUtils.getUser().getUserName()+"审核同意-->备注:["+info+"]");
            }else {
                //审核通过修改相应的状态 修改ServiceItem和carPackageAudit的状态为审核通过
                serviceItemMapper.updateAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                carPackageAuditMapper.updateStatus(id,CarPackageAudit.STATUS_PASS);
                carPackageAudit.setInfo(carPackageAudit.getInfo()+"<br>"+ ShiroUtils.getUser().getUserName()+"审核同意-->备注:["+info+"]");
            }

        }else{
            //审批失败 修改ServiceItem的状态为重新调整 carPackageAudit状态为拒绝状态
            serviceItemMapper.updateAuditStatus(carPackageAudit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
            carPackageAuditMapper.updateStatus(id,CarPackageAudit.STATUS_REJECT);
            carPackageAudit.setInfo(carPackageAudit.getInfo()+"<br>"+ ShiroUtils.getUser().getUserName()+"审核拒绝-->备注:["+info+"]");
        }
        //最后修改carPackageAudit审批时间为当前时间
        carPackageAudit.setAuditTime(new Date());
        carPackageAuditMapper.updateAuditResult(carPackageAudit);
    }
}
